import { cartList } from "@src/api/coupon";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import cart from "../../../../store/cart";
import { getShopStatus } from "@src/api/catering";

Component({
  options: {
    addGlobalClass: true,
  },
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: cart,
      fields: ["cartList", "num", "totalFee", "shopId"],
      actions: ["addCart", "reduceCart", "clearCart"],
    },
  ],
  observers: {
    shopId: function (shopId) {
      if (shopId) {
        this.setShopStatus();
      }
    },
  },
  data: {
    showDetail: false,
    isOpenTime: true,
  },
  methods: {
    onLoad() {},
    handleRevertShowStatus() {
      if (!this.setShopStatus()) return;
      this.setData({ showDetail: !this.data.showDetail });
    },
    handleStop() {
      return true;
    },
    handleClearCart() {
      wx.showModal({
        title: "",
        content: "清空购物车",
        confirmText: "清空",
        showCancel: true,
        success: (res) => {
          if (res.confirm) {
            this.clearCart();
            this.setData({ showDetail: false });
          }
        },
      });
    },
    async handleToPay() {
      this.setShopStatus().then((res) => {
        if (res) {
          this.triggerEvent("pay");
        }
      });
    },
    handleMinus(e) {
      let item = e.currentTarget.dataset.item;
      for (let i = 0; i < item.count - Number(e.detail); i++) {
        this.handleOp("reduce", item);
      }
    },
    handlePlus(e) {
      let item = e.currentTarget.dataset.item;
      for (let i = 0; i < Number(e.detail) - item.count; i++) {
        this.handleOp("add", item);
      }
    },
    handleOp(op, item) {
      // let { op, item } = e.currentTarget.dataset;
      if (op === "add") {
        delete item.count;
        this.addCart(item);
      } else {
        this.reduceCart(item);
        if (this.data.num === 0) {
          this.setData({ showDetail: false });
        }
      }
    },
    async setShopStatus() {
      let isOpenTime = true;
      let res = await getShopStatus({ shopId: this.data.shopId });
      let { isOpen, status, disabled } = res.data;
      isOpenTime =
        isOpen == true && (status == 1 || status == 2) && disabled == false
          ? true
          : false;
      this.setData({ isOpenTime });
      return isOpenTime;
    },
  },
});
